package org.lbm.flow.context;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 工作流执行上下文
 *
 * @author insist
 * @since 2025-08-01
 * 用于在工作流执行过程中传递和管理数据
 */
public class FlowContext {

    private final String flowId;
    private final long startTime;
    private final AtomicLong nodeCounter;
    private final Map<String, Object> variables;
    private final Map<String, Object> metadata;

    public FlowContext(String flowId) {
        this.flowId = flowId;
        this.startTime = System.currentTimeMillis();
        this.nodeCounter = new AtomicLong(0);
        this.variables = new ConcurrentHashMap<>();
        this.metadata = new ConcurrentHashMap<>();
    }

    /**
     * 获取工作流ID
     */
    public String getFlowId() {
        return flowId;
    }

    /**
     * 获取开始时间
     */
    public long getStartTime() {
        return startTime;
    }

    /**
     * 获取执行时长（毫秒）
     */
    public long getExecutionTime() {
        return System.currentTimeMillis() - startTime;
    }

    /**
     * 生成下一个节点ID
     */
    public String nextNodeId() {
        return "node_" + nodeCounter.incrementAndGet();
    }

    /**
     * 设置变量
     */
    public void setVariable(String key, Object value) {
        variables.put(key, value);
    }

    /**
     * 获取变量
     */
    @SuppressWarnings("unchecked")
    public <T> T getVariable(String key) {
        return (T) variables.get(key);
    }

    /**
     * 获取变量，如果不存在则返回默认值
     */
    @SuppressWarnings("unchecked")
    public <T> T getVariable(String key, T defaultValue) {
        return (T) variables.getOrDefault(key, defaultValue);
    }

    /**
     * 检查变量是否存在
     */
    public boolean hasVariable(String key) {
        return variables.containsKey(key);
    }

    /**
     * 移除变量
     */
    public Object removeVariable(String key) {
        return variables.remove(key);
    }

    /**
     * 获取所有变量
     */
    public Map<String, Object> getVariables() {
        return new ConcurrentHashMap<>(variables);
    }

    /**
     * 设置元数据
     */
    public void setMetadata(String key, Object value) {
        metadata.put(key, value);
    }

    /**
     * 获取元数据
     */
    @SuppressWarnings("unchecked")
    public <T> T getMetadata(String key) {
        return (T) metadata.get(key);
    }

    /**
     * 获取所有元数据
     */
    public Map<String, Object> getMetadata() {
        return new ConcurrentHashMap<>(metadata);
    }

    /**
     * 清空所有数据
     */
    public void clear() {
        variables.clear();
        metadata.clear();
    }
}
